package com.cjzuji.rental.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.cjzuji.rental.Config.ProjectConfig;
import com.cjzuji.rental.dao.RiskApprovilDao;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.mapper.OrderUserMapper;
import com.cjzuji.rental.pojo.OrderUser;
import com.cjzuji.rental.pojo.Orders;
import com.cjzuji.rental.pojo.RiskApprovil;
import com.cjzuji.rental.service.RiskApprovilService;
import com.cjzuji.rental.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RiskApprovilServiceImpl implements RiskApprovilService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderUserMapper orderUserMapper;
    @Autowired
    ProjectConfig projectConfig;
    @Autowired
    RiskApprovilDao riskApprovilDao;

    private static final Logger logger = LoggerFactory.getLogger(RiskApprovilServiceImpl.class);
    //风控授信
    @Override
    public String riskApproval(Orders orders, String orderId) {
        //获取风控优品信息
        QueryWrapper<OrderUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_id", orders.getId());
        //这里注入OrderUserMapper，根据orderId查询
        OrderUser orderUser = orderUserMapper.selectOne(queryWrapper);
        JSONObject content = new JSONObject();
        content.put("idcard_no", orderUser.getIdCard());    // 身份证号
        content.put("mobile", orders.getPhone());      // 手机号
        content.put("name ", orders.getRealName());    // 姓名
        content.put("receive_address", orderUser.getAddressInfo());   //收货地址
        content.put("rec_prov", orderUser.getProvince());    //省份
        content.put("re_city", orderUser.getCity());     // 市
        content.put("rec_area", orderUser.getCounty());   // 区
        content.put("orderNo", orderId);  // 订单号
        //content.put("leaseScheme", "1");   //租赁类型
        content.put("rent_start", orders.getRentStartTime());    //租借开始时间
        content.put("unrent_time", orders.getRentLastTime());   //租借结束时间
        content.put("userid", orders.getLeaseTerm());   //用户ID
        content.put("credit_time ", DateUtil.getStandardNowTime());   //授信时间
        String creditId =  java.util.UUID.randomUUID().toString().replace("-", "");
        content.put("credit_id ", creditId);  //授信ID
        content.put("releaseChannel", "1");  //渠道
        String contentStr = JSONObject.toJSONString(content);
        logger.info("风控审批入参信息：{}",contentStr);
        //AES加密
        String encryptedContent = AESUtilsOfThird.encryptAES(contentStr, projectConfig.getAESKEY());
        logger.info("AES加密后的内容：{}",encryptedContent);
        //MD5
        String md5Content = MD5.getMd5(encryptedContent);
        logger.info("MD5加密后的内容：{}",md5Content);
        //RSA sign
        String signString = "";
        try {
            signString = RSAUtil.sign(md5Content, projectConfig.getPRIVATEKEY(), false);
            logger.info("得到的签名是：" + signString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject params = new JSONObject();
        params.put("source_id", projectConfig.getSOURCEID());
        params.put("event_code", projectConfig.getAPPROVALEVENTCODE());
        params.put("signature", signString);
        params.put("content", encryptedContent);
        logger.info("风控接口请求入参:{}",JSONObject.toJSONString(params));
        String result = HttpClientUtil.postJson(projectConfig.getURL(), params);
        logger.info("风控接口响应:"+result);
        JSONObject resultObj = JSONObject.parseObject(result);
        //判断接口是否调用成功
        if (resultObj.getString("status").equals("1000")){
            String needDecryptString = resultObj.getString("content");
            String resultContentStr = AESUtilsOfThird.decryptAES(needDecryptString, projectConfig.getAESKEY());
            logger.info("返回Content: " + resultContentStr);
            JSONObject contentObject = JSONObject.parseObject(resultContentStr);
            RiskApprovil approval = riskApprovilDao.getOne(new QueryWrapper<RiskApprovil>().eq("order_id",orderId).last("limit 1"));
            if (approval== null){
                approval = new RiskApprovil();
            }
            approval.setOrderId(orders.getId());
            approval.setOrdersId(orderId);
            approval.setContent(resultContentStr);
            approval.setApprovalStatus(ObjectUtils.isNotEmpty(contentObject) ?contentObject.getString("approval_status"):null);
            approval.setCreditId(creditId);
            riskApprovilDao.saveOrUpdate(approval);
            return creditId;
        }else {
            return null;
        }
    }
    /**
     *  查询风控授信处理结果
     *
     * @param creditId  查询引擎授信处理结果
     * @return
     */
    public String queryApproval(String creditId) {
        JSONObject content = new JSONObject();
        content.put("credit_id", creditId);
        String contentStr = JSONObject.toJSONString(content);
        logger.info("查询引擎授信处理结果入参:"+contentStr);
        // AES
        String encryptedContent = AESUtilsOfThird.encryptAES(contentStr, projectConfig.getAESKEY());
        logger.info("AES加密后的内容："+encryptedContent);
        // MD5
        String md5Content = MD5.getMd5(encryptedContent);
        logger.info("md5加密后的内容："+md5Content);
        // RSA sign
        String signString = "";
        try {
            signString = RSAUtil.sign(md5Content, projectConfig.getPRIVATEKEY(), false);
            logger.info("得到的签名是：" + signString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject params = new JSONObject();
        params.put("source_id", projectConfig.getSOURCEID());
        params.put("event_code", projectConfig.getAPPROVALRESULTEVENTCODE());
        params.put("signature", signString);
        params.put("content", encryptedContent);
        logger.info("查询引擎授信处理结果请求入参:{}",JSONObject.toJSONString(params));
        String result = HttpClientUtil.postJson(projectConfig.getQUERYURL(), params);
        logger.info("查询引擎授信处理结果响应:"+result);
        JSONObject resultObj = JSONObject.parseObject(result);
        //判断接口调用是否成功
        if (resultObj.getString("status").equals("1000")){
            String needDecryptString = resultObj.getString("content");
            String resultContentStr = AESUtilsOfThird.decryptAES(needDecryptString, projectConfig.getAESKEY());
            logger.info("返回Content: " + resultContentStr);
            JSONObject contentObject = JSONObject.parseObject(resultContentStr);
            RiskApprovil approval = riskApprovilDao.getOne(new QueryWrapper<RiskApprovil>().eq("credit_id",creditId).last("limit 1"));
            if (approval== null){
                approval = new RiskApprovil();
            }
            approval.setMassage(resultContentStr);
            approval.setStatus(ObjectUtils.isNotEmpty(contentObject) ?contentObject.getString("status"):null);
            approval.setCreditId(creditId);
            riskApprovilDao.saveOrUpdate(approval);
            return resultContentStr;
        }else {
            return null;
        }

    }

}
